package com.grad.webstudy.utils;

import com.grad.webstudy.constants.FileContants;
import com.grad.webstudy.enums.ExceptionEnums;
import com.grad.webstudy.exceptions.CustomException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/1/27 22:08.
 */
public class FileUtils {

    public static String destFilePath=""; //文件真实位置

    /**
     * 通用上传文件方法
     *
     * @param files
     * @param filePath
     * @return
     * @throws IOException
     */
    public static List<String> upload(MultipartFile[] files, String filePath,String... destPath) {

        List<String> fileUrls = new ArrayList<>();

        if (files != null && files.length > 0) {

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    throw new MultipartException("文件为空");
                }

                String oldFileName = file.getOriginalFilename();
                System.out.println(oldFileName);
                System.out.println(file.getName());
                System.out.println(file.getSize());


                String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
                String newFileName = DateUtils.toString(new Date(),"yyyyMMddHHmmss") + getRandomFileName() + suffix;

                File folder = new File(filePath);
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                String fileUrl = FileContants.FILE_URL + newFileName;
                System.out.println(fileUrl);
                File dest = new File(filePath + newFileName);
                try {
                    file.transferTo(dest);
                    destFilePath=filePath + newFileName;
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new CustomException(ExceptionEnums.CUSTOM_ERROR.getCode(),
                            "IO异常"+e.getCause());
                }
                fileUrls.add(fileUrl);

            }

        }
        return fileUrls;
    }

    public static String getRandomFileName(){
        String numberList = "asdfghjklzxcvbnmqwertyuiopASDFGHJKLZXCVBNMQWERTYUIOP1234567890";
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(numberList.length());
            char c = numberList.charAt(index);
            result += c;
        }
        return result;
    }
}
